<template>
  <el-upload-hook
    ref="upload"
    :file-list="fileList"
    action="api/system/file/upload"
    :before-upload="onBeforeUpload"
    :on-error="onError"
    :class="{hide:disabled}"
    multiple
    :headers="headers"
    :on-success="handleSuccess"
    :list-type="listType"
  >

    <template>
      <pure-button label="上传文件" size="small" icon="upload" />
      <div slot="tip" class="el-upload__tip">
        <i class="el-icon-warning-outline" />
        <span>支持：.jpg .jpeg .png .gif .rar .zip .doc .docx .xls .xlsx .pdf .txt .pptx ，单个文件不能超过100M</span>
      </div>
    </template>
  </el-upload-hook>
</template>

<script>
import ElUploadHook from './elementui/index.vue';
import ServerError from '@/common/utils/errorHandler/serverError';
export default {
  name: 'PureUpload',
  components: {
    ElUploadHook,
  },
  props: {
    value: {
      type: Array,
      default: function () {
        return [];
      },
    },
    listType: {
      type: String,
      default: 'text',
    },
    disabled: {
      type: Boolean,
      default: false,
    },

  },
  data() {
    return {
      acceptTypeList: [
        'jpg',
        'jpeg',
        'png',
        'gif',
        'rar',
        'zip',
        'doc',
        'docx',
        'xls',
        'xlsx',
        'pdf',
        'txt',
        'pptx',
      ],
      maxSize: 100,
      currentFiles: null,
    };
  },
  computed: {

    headers() {
      return { Authorization: process.env.VUE_APP_TOKEN, };
    },
    fileList() {
      return this.value;
    },
    Disabled() {
      return this.disabled || (this.elForm || {}).disabled;
    },
  },
  methods: {
    onBeforeUpload(file) {
      const { name, size, } = file;
      const limitSize = 1024 * 1024 * this.maxSize;
      console.log(name, size);
      const suffix = name.substring(name.lastIndexOf('.') + 1);
      const isAcceptSize = size < limitSize;

      const isAcceptType = this.acceptTypeList.includes(suffix);
      if (!isAcceptType) {
        this.$message({
          message: `不支持上传${suffix}格式文件`,
          type: 'warning',
        });
        return false;
      }
      if (!isAcceptSize) {
        this.$message({
          message: `上传文件大小不能超过${this.maxSize}M!`,
          type: 'warning',
        });
        return false;
      }
      return true;
    },
    onError(err, file, fileList) {
      this.handleSuccess(null, file, fileList);
      Promise.reject(new ServerError({ message: '上传失败:' + err, }));
    },
    handleSuccess(res, file, fileList) {
      const realFileList = [];
      if (this.isAllSuccess(fileList)) {
        fileList.map((item, index, arr) => {
          (item.response && realFileList.push(this.unifiedFileFormat(item))) || (item.status === 'success' && realFileList.push(this.unifiedFileFormat(item)));
        });
        console.log(realFileList);
        this.$emit('input', realFileList);
        this.$emit('change', realFileList);
      }
    },
    // 判断是否所有文件都已完成上传
    isAllSuccess(fileList) {
      if (fileList.length) {
        return fileList.every((file) => file.status === 'success');
      }
      return false;
    },
    unifiedFileFormat(file) {
      const response = file.response;
      console.log(file);
      if (response) {
        const fileData = response.data[0];
        return {
          name: fileData.name,
          url: fileData.url,
          id: fileData.id,
          uid: fileData.uid,
        };
      } else {
        return {
          name: file.name,
          url: file.url,
          id: file.id,
          uid: file.uid,
        };
      }
    },
    removeFile(file) {
      this.$refs.upload.handleRemove(file);
    },
    onRemoveFile(file, list) {
      this.$emit('input', JSON.stringify(list));
      this.$emit('change', JSON.stringify(list));
    },
  },
};
</script>

<style lang="scss" scoped>
 @import "~@/common/styles/theme/handle.scss";
.el-upload__tip {
  font-size: 14px;
  padding: 6px;
  line-height: 22px;
  @include font_color_imp('color-special');
  @include background_color_imp('color-assist-3');
}
</style>
